﻿using Basic.RateLimit.Handler;
using Basic.RateLimit.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;

namespace System
{

    public static class RateLimitExtension
    {
        public static IServiceCollection AddBasicRateLimit(this IServiceCollection services, IConfigurationSection section)
        {
            var dict = section.Get<Dictionary<string, int>>() ?? new Dictionary<string, int>();
            Dictionary<string, RateLimitHandler> rules = new Dictionary<string, RateLimitHandler>();
            foreach (var kv in dict)
            {
                rules.Add(kv.Key, new RateLimitHandler(kv.Value, EnumRateLimitingUnit.Minutes));
            }
            RateLimitFactory singleton = new RateLimitFactory();
            singleton.AddRule(rules);
            return services.AddSingleton(singleton).AddTransient<RateLimitMiddleware>();
        }

        public static IApplicationBuilder UseBasicRateLimit(this IApplicationBuilder app)
        {
            return app.UseMiddleware<RateLimitMiddleware>();
        }
    }
}